# coding=utf-8

import Metashape
import json

## Initialize Project
doc = Metashape.app.document
projectFile="/mnt/sdb1/home/hzy/projects/XXH2019.psx"
doc.open(projectFile)

chunks = Metashape.app.document.chunks
doc.read_only = False

for chunk in chunks:
    print("Start Processing Chunk:" + chunk.label)

    # Step 1
    #chunk.matchPhotos(downscale=1, generic_preselection=True, reference_preselection=False)
    #chunk.alignCameras()
    #doc.save()

    # Step 2
    #if(len(chunk.depth_maps_sets) < 1):
    #    chunk.buildDepthMaps(downscale=4, filter_mode=Metashape.AggressiveFiltering)
    #    doc.save()
    #    print("Finish Build Depth Maps for Chunk:" + chunk.label)
    #else: 
    #    print("Chunk:"+chunk.label+" has Depth Maps")
    #
    #if(len(chunk.dense_clouds)<1):
    #    chunk.buildDenseCloud()
    #    print("Finsish Build Dense Cloud...")
    #    doc.save()
    #else:
    #    print("Chunk:"+chunk.label+" has Dense Clouds")

    #step 3
    #chunk.buildTiledModel()
    #doc.save()
    #print("Chunk:"+chunk.label+" Complete Build Tiled Model!!!") 
    #chunk.buildDem()
    #doc.save()
    #print("Chunk:"+chunk.label+" Complete Build DEM!!!")
    
    #step 4
    chunk.buildOrthomosaic(surface_data=Metashape.ElevationData)
    doc.save()
    print("Chunk:"+chunk.label+" Complete Build Orthomosaic!!")
   # chunk.buildOrthomosaic()
   # doc.save(projectFile,[chunk])
   # chunk.buildUV(mapping_mode=Metashape.GenericMapping)
   # doc.save(projectFile,[chunk])
   # chunk.buildTexture(blending_mode=Metashape.MosaicBlending, texture_size=4096)
   # doc.save(projectFile,[chunk])
    #print("Complete Processing Chunk:" + chunk.label)
    #doc.save()

print("Saving the project....")
doc.save()
print("Finish Processing the project.")
